﻿using SaaS.Cache.Logs;
using SaaS.Core;
using SaaS.Model.Entity.Logs;
using System;
using System.Text;
using SaaS.Core.Logger;
using SaaS.Core.Helper;
using XCore.Dependency;

namespace SaaS.Scheduler.Action
{
    public class LoggerAction : SchedulerServiceBase
    {
        private readonly LoggerService _loggerService;
        private readonly LoggerCacheService _loggerCacheService;
        public LoggerAction()
        {
            _loggerService = IocCollection.Resolve<LoggerService>();
            _loggerCacheService = IocCollection.Resolve<LoggerCacheService>();
        }
        public override TimeSpan Time => TimeSpan.FromSeconds(60);

        public override string Name => "错误日志";

        public override void Invoke()
        {
            Stopwatch.Start();
            int count = 0;
            StringBuilder sb = new StringBuilder();
            foreach (var item in _loggerCacheService.GetLogs<ErrorLog>(CoreSetting.SYSTEM_ERROR))
            {
                if (_loggerService.Save(item))
                {
                    count++;
                    sb.Append($"{item.Appdomin}发送错误异常");
                }
            }

            //推送至总后台
            HttpClientHeler.Hub(sb.ToString());
            foreach (var item in _loggerCacheService.GetLogs<TraceLog>(CoreSetting.SYSTEM_TRACE))
            {
                if (_loggerService.Save(item))
                {
                    count++;
                }
            }
            if (count > 0) WriteLine("同步成功", count, Stopwatch.ElapsedMilliseconds);
            Stopwatch.Reset();
        }
    }
}
